# parse data to class

import re

from input import lesson_list, Lesson
from utils import cal_date

lesson_pattern = re.compile(r'(\d.*周(?:\([双|单]\))?),?(\d.*周)?(?:\([双|单]\))?')
lesson_pattern2 = re.compile(r'((\d.*周,)+\d.*周)')
class_pattern = re.compile(r'\w{10}-\d{2}A?')
classroom_number_pattern = re.compile(r'([A-Z]\d-\d+)|(图书馆\d{3})') # A4-302
# 2024软件技术专科3班;2024软件技术专科4班;2024软件技术专科7班
teach_class_pattern = re.compile(r'教学班组成.*20\d{2}.*班')
period_pattern = re.compile(r'\((\d+-\d+)节\)')
number_pattern = re.compile(r'(\d+)')
class_number_map = dict()


def _format_week(week):
    week = week.replace('周','').replace('(', '-').replace(')', '').replace('单', '1').replace('双', '2')
    return week


def handle(lesson_data, day, content):
    lesson_items = [x.strip() for x in content.split('\n') if x != '']
    lesson = [day]
    for i in range(len(lesson_items)):
        lesson_item = lesson_items[i]
        # 第几周范围
        if i == 1:
            m_period = period_pattern.search(lesson_item)
            if m_period:
                lesson.append(m_period.group(1))
            m = lesson_pattern.search(lesson_item)
            m2 = lesson_pattern2.search(lesson_item)
            if m or m2:
                week_list = _format_week(m.group(1))
                if ',' in week_list:
                    week_list = week_list.split(',')
                else:
                    week_list = [week_list]
                if m.group(2):
                    week_list.append(_format_week(m.group(1)))
                lesson.append(week_list)
        # elif i == 5:
        #     student_number_m = number_pattern.search(lesson_item)
        #     if student_number_m:
        #         lesson.append(int(student_number_m.group(1)))
        else:
            class_m = class_pattern.search(lesson_item) # 3080900225-07
            classroom_number_m = classroom_number_pattern.search(lesson_item) # A4-203
            teach_classes = teach_class_pattern.findall(lesson_item)
            if class_m or classroom_number_m or teach_classes:
                if classroom_number_m:
                    lesson.append(classroom_number_m.group(0))
                elif lesson[1].startswith(('软件编程实践','软件技术服务实践','软件工程专业实践')):
                    lesson.append('学社课')
                else:
                    lesson.append('混合式')
                if class_m:
                    lesson.append(class_m.group(0))
                else:
                    lesson.append('None')
                if teach_classes and len(teach_classes) > 0:
                    lesson.append(';'.join(teach_classes))
            else:
                lesson.append(lesson_item)
    lesson_data.append(lesson)



def parse():
    lesson_data = []
    for day, contents in lesson_list.items():
        for content in contents:
            if content.count('\n\n') > 1:
                items = content.split('\n\n')
                for i in range(len(items)-1,-1,-1):
                    if i-1 >= 0:
                        tmp = items[i-1].split('\n')
                        class_name = tmp.pop() # 取出最后一项，作为课程名
                        if i == len(items) - 1: # 最后一门课，直接取内容
                            handle(lesson_data, day, class_name + '\n' + items[i])
                        else: # 不是最后一门课，需要把最后一项（下一门课的名称）去掉
                            tmp = items[i].split('\n')[:-1]
                            handle(lesson_data, day, class_name + '\n' + '\n'.join(tmp))
            else:
                handle(lesson_data, day, content)
    return lesson_data

def group_by_day():
    total_lessons = []
    lesson_data = parse()
    for lesson in lesson_data:
        lessons = cal_date(lesson)
        total_lessons = total_lessons + lessons
    total_lessons.sort(key=lambda total_lessons: (total_lessons[1],total_lessons[3])) #按日期和上课时间排序
    # 重新遍历按时间排好序的列表，加入每门课程是第几讲
    for lesson in total_lessons:
        for i in range(len(lesson)):
            if i < 3:
                continue
            lesson_item = lesson[i]
            class_m = class_pattern.search(str(lesson_item))  # 3080900225-07
            if class_m:
                class_number = class_m.group(0)  # 教学班编号
                course = lesson[5]  # 课程名
                key = course + class_number  # 以课程名和班级为key，作为唯一区分课程的第几节课标志
                if key.endswith('A'):
                    key = key[:-1]
                time_ = int(class_number_map.get(key, 0))  # 获取第几次课，如果没有，则为0
                time_ += 1
                class_number_map[key] = time_
                lesson.insert(6,f'第{str(time_)}讲')
                break
    for lesson in total_lessons:
        # if not lesson[6].startswith("第"):
        #     lesson.insert(6, '学社课')
        # if lesson[9] != 'None' and not lesson[9][0].isdigit():
        #     # 教学班编号
        #     lesson[9] = 'None'
            # 教学班
        if not lesson[10].startswith('教学班组成'):
            lesson.insert(10,'无')
    return total_lessons